<?php
class advModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //getdocument
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    public function getNewDocs($docid)
    {
        $where = " WHERE `docid`=" . intval($docid);
        $sql   = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs    = $this->db->getrow($sql);
        if ($rs) {

            $file_url        = $this->c['doc_host'] . date("Ymd", $rs['create_time']) . "/" . date("H", $rs['create_time']) . "/" . date("i", $rs['create_time']) . "/" . $rs['filename'];
            $doc             = $rs;
            $doc['file_url'] = $file_url;
            return $doc;
        } else {
            return false;
        }

    }

    //获取单个商品
    public function getSingleArticle($id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}adv WHERE `id`=" . intval($id) . "   LIMIT 1";
        $data = $this->db->getrow($sql);

        return $data;

    }

    public function removeArticle($id)
    {
        if ($id) {
            $sql = "DELETE FROM {$this->_prefix['primary']}adv WHERE `id`=" . intval($id) . "   LIMIT 1";
            $res = $this->sql($sql);
            if ($res) {
                $data['code'] = 200;
                $data['msg']  = "删除广告成功";
            } else {
                $data['code'] = 900;
                $data['msg']  = "删除广告失败";
            }
        } else {
            $data['code'] = 901;
            $data['msg']  = "删除广告失败,ID不存在";

        }
        return $data;
    }

    //广告列表
    public function getArticles($para, $page = 1, $pagesize = 10)
    {
        $where .= " 1=1 ";

        if ($para) {

            if ($para['caid'] != '') {

                $where .= " AND `caid`=" . $para['caid'];
            }

            if ($para['keyword'] != '') {
                $where .= "   AND `title` LIKE '%" . $para['keyword'] . "%'";
            }

            if (isset($para['position']) && $para['position'] > 0) {
                $where .= " AND `position`=" . $para['position'];
            }

            if (isset($para['status'])) {
                $where .= "  AND `status`=" . $para['status'];
            }

        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}adv WHERE " . $where;
        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`sorts`ASC ,`ctime` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}adv WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            foreach ($rs as $key => $val) {
                if ($val['caid'] > 0) {
                    $sql  = "SELECT `name` FROM {$this->_prefix['primary']}goods_category WHERE caid=" . $val['caid'];
                    $cate = $this->db->getrow($sql);

                    $rs[$key]['cate_name'] = $cate['name'];
                }
            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
        );
    }
    //排序 广告列表
    public function getAdvLists($position)
    {
        if ($position) {
            $sql = "SELECT * FROM {$this->_prefix['primary']}adv WHERE  position=" . $position . " ORDER BY `sorts` ASC,ctime DESC ";
            $rs  = $this->sql($sql);
            return $rs;
        }
    }

    //修改排序
    public function saveAdvSort($da)
    {
        $code     = 900;
        $position = intval($da['position']);

        if ($da) {
            if (!empty($da['value']) && !empty($position)) {
                $ids = json_decode($da['value'], true);

                foreach ($ids as $key => $val) {

                    $sql = "UPDATE {$this->_prefix['primary']}adv SET sorts=" . $key . " WHERE id=" . $val['id'] . " AND position=" . $position;
                    $this->sql($sql);
                }

                $code = 200;
            }

        }
        return $code;
    }
    //保存文章
    public function saveArticle($da, $file, $adv_id = 0)
    {
        $code = 900;

        $savegoods         = true; //执行商品保存的标记
        $field['title']    = addslashes(htmlspecialchars(trim($da['title'])));
        $field['content']  = addslashes(htmlspecialchars(trim($da['content'])));
        $field['goods_id'] = addslashes(htmlspecialchars(trim($da['goods_id'])));
        $field['shop_price']       = number_format($da['shop_price'], 2, '.', '');
        $field['market_price']     = number_format($da['market_price'], 2, '.', '');
        $field['sorts']    = intval($da['sorts']);
        if(intval($da['pic'])){
            $field['pic']      = intval($da['pic']);
        }
        $field['caid']     = intval($da['caid']);
       // dd($field);
        $field['position'] = intval($da['position']);
        $field['wechat_url']      = addslashes(htmlspecialchars(trim($da['wechat_url'])));
        $field['app_url']      = addslashes(htmlspecialchars(trim($da['app_url'])));

        //如果选择了缩略图文件
        if ($file['pic']['tmp_name'] != "" && $file['pic']['size'] > 0) {
            $savegoods = false;
            $msg       = "上传图片失败";
            if (in_array($file['pic']['type'], $this->c['upload']['mime'])) {

                if ($file['pic']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic']['tmp_name'], $filepath)) {
                                $this->upload->mt($filepath, $filepath, 600, 600);
                                $docid = $this->saveDocument($file['pic']['name'], $filename, @filesize($filepath), $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic'] = $docid;
                                    $savegoods    = true;
                                    $msg          = "";
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }
/*         $goods_ids = explode(',', $field['goods_id']);
if (!empty($goods_ids)) {
foreach ($goods_ids as $key => $val) {
$sql      = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}goods_data WHERE goods_id=" . $val . " and     is_delete=0 and is_on_sale=1";
$goods_id = $this->db->getone($sql);

if (!$goods_id) {
$code = 901;

$msg          = "商品ID为" . $val . "已下架或者不存在";
$data['code'] = $code;
$data['msg']  = $msg;
return $data;
}
}
}
 */
        //保存信息
        if ($field['title'] != "" && $savegoods) {

            $code = 403;

            //开始事务
            $this->db->begin();
            $rollback = true;

            //修改
            if ($adv_id > 0) {
                $field['status'] = intval($da['status']);
                //print_r($field);die;
                //其他必须字段

                $msg = "修改广告失败";

                //修改文章
                $sql = "UPDATE {$this->_prefix['primary']}adv SET ";
                foreach ($field as $key => $value) {
                    $upsql[] = "`" . $key . "`='" . $value . "'";
                }
                $sql .= implode(",", $upsql) . " WHERE `id`=" . $adv_id;
//print_r($sql);die;
                $rcnum = $this->sql($sql);
                if ($rcnum) {

                    $msg  = "修改广告成功";
                    $code = 200;
                    $this->db->commit();
                    $rollback = false;

                }

            }
            //新增
            else {
                $msg = "添加广告失败";
                //其他必须字段
                $field['ctime'] = $_SERVER['REQUEST_TIME'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }

                //插入文章
                $sql   = "INSERT INTO {$this->_prefix['primary']}adv (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
                $advID = $this->sql($sql);

                if ($advID > 0) {
                    $code = 200;
                    $msg  = "添加广告成功";
                    $this->db->commit();
                    $rollback = false;

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }
        /* $data['code'] = $code;
        $data['msg']  = $msg; */
        return $code;
    }
    //获取所有类别
    public function getGoodsCategory($caid = 0, $isfucaid = false, $shopid = 1)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        if ($shopid > 0) {
            $tsql = " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //获取所有类别
    public function getPcategory()
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1 AND `fucaid`=0  ORDER BY `sort` ASC,`stat` ASC,`caid` ASC ";

        $data = $this->sql($sql);

        return $data;
    }
//上传图片
    public function upImg($file)
    {
        $data = array();

        if ($file['tmp_name'] != "" && $file['size'] > 0) {

            if (in_array($file['type'], $this->c['upload']['mime'])) {

                if ($file['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;

                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                                $docid = $this->saveDocument($file['name'], $filename, $file['size'], $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {

                                    $data['code']   = 200;
                                    $data['msg']    = "上传成功";
                                    $data['path']   = $this->c['doc_host'] . date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/" . $filename;
                                    $data['pic_id'] = $docid;

                                    return $data;

                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                    $msg = '';

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }
    }

    //获取所有类别
    public function getCategory($caid = 0, $isfucaid = false)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}article_category WHERE  `stat`<3" . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //保存分类排序
    public function saveCategorySort($da)
    {
        $code = 900;
        if ($da['value'] != "") {
            $ids = json_decode($da['value']);
            foreach ($ids as $k => $r) {
                $sql = "UPDATE {$this->_prefix['primary']}article_category SET `sort`=" . $k . " WHERE `caid`=" . intval($r->id);
                $this->sql($sql);
            }
            $code = 200;
        }
        return $code;
    }

    //保存文档
    public function saveDocument($name, $filename, $filesize, $format, $create_time)
    {
        $sql = "INSERT INTO {$this->_prefix['primary']}documents
        (`name`,`filename`,`filesize`,`format`,`create_time`) VALUES
        ('" . $name . "','" . $filename . "'," . $filesize . ",'" . $format . "'," . $create_time . ")";

        $docid = $this->sql($sql);
        return $docid;
    }

    //保存分类
    public function saveCategory($da, $file, $caid = 0)
    {

        $code   = 900;
        $name   = addslashes(htmlspecialchars(trim($da['name'])));
        $stat   = intval($da['stat']);
        $fucaid = intval($da['fucaid']);
        //分类logo处理
        if ($file['pic_big']['tmp_name'] != "" && $file['pic_big']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['pic_big']['type'], $this->c['upload']['mime'])) {

                if ($file['pic_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_big']['tmp_name'], $filepath)) {
                                $docid = $this->saveDocument($file['pic_big']['name'], $filename, $file['pic_big']['size'], $format, $_SERVER['REQUEST_TIME']);
                                if ($docid > 0) {
                                    $field['pic_docid']  = $docid;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['pic_big']['name'];
                                    $pic_big['format']   = $format;
                                    $savegoods           = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }
        //修改
        if ($caid > 0) {
            $sql = "SELECT * FROM {$this->_prefix['primary']}article_category WHERE `caid`=" . intval($caid) . "  AND `stat`<3";
            $rs  = $this->db->getrow($sql);

            if ($rs) {
                if ($docid) {
                    $s = ',`docid`=' . $docid . '';
                } else {
                    $s = '';
                }
                $sql = "UPDATE {$this->_prefix['primary']}article_category SET `stat`=" . $stat . ",`fucaid`=" . $fucaid . ",`name`='" . $name . "',`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . $s . " WHERE `caid`=" . $rs['caid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 404;
            }
        }
        //新增
        else {
            if ($da['name'] != "") {

                $sql = "INSERT INTO {$this->_prefix['primary']}article_category
                    (`name`,`fucaid`,`stat`,`last_staffedit`,`docid`) VALUES
                    ('" . $name . "'," . $fucaid . "," . $stat . "," . $_SERVER['REQUEST_TIME'] . "," . $docid . ")";

                $rd = $this->sql($sql);

                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            }
        }
        return $code;

    }

    /**
     * 图片上传
     * @param $files  待上传的图片
     * @return array  图片路径和图片id
     */
    public function uploadImg($files)
    {
        $code  = 706;
        $error = '';
        //创建目录
        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['date'])) {
            mkdir($dir['date']);
        }

        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['hour'])) {
            mkdir($dir['hour']);
        }

        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['minute'])) {
            mkdir($dir['minute']);
        }
        if (file_exists($dir['minute'])) {

            $doc_host = $this->c['doc_host'] . date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/";

            if (in_array($files['type'], $this->c['upload']['mime'])) {

                if ($files['size'] <= $this->c['upload']['size']) {

                    $format = explode(".", $files['name']);
                    $format = strtolower($format[count($format) - 1]);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        $filename = md5($_SERVER['REQUEST_TIME'] . $files['tmp_name'] . $files['name']) . "." . $format;
                        $path     = $dir['minute'] . "/" . $filename;
                        if (move_uploaded_file($files['tmp_name'], $path)) {

                            $code = 200;
                            $data = $this->saveDocument('商品主图', $filename, $files['size'], $format, $_SERVER['REQUEST_TIME']);

                            $img_url = $doc_host . $filename;
                        } else {
                            $error = 705; //上传失败
                        }

                    } else {
                        $error = 703; //图片格式错误
                    }

                } else {
                    $error = 704; // 图片太大
                }

            } else {
                $error = 703; //图片格式错误
            }

            @unlink($files['tmp_name']);

        }
        return array('code' => $code, 'data' => $data, 'url' => $img_url, 'error' => $error);

    }
}
